import logging

import neon.db as db
import neon.atom as atom
import neon.sql_adapt as sql_adapt
import neon.guid as guid
import neon.version as version

import util.testtool as testtool

l = logging.WARN
# l = logging.DEBUG
logging.basicConfig(level=l)

log = logging.getLogger('unit-test')

init = True
store_type = ':memory:'

backend = db.Sqlite(store_type, init)
backend.execute('CREATE TABLE tab1 (guid, id)')
backend.execute('CREATE TABLE tab2 (guid, id1, id2, id3, id4)')

atom_store = atom.AtomStore(None, backend, init, None)

class DummyNeon:
    def atom_store(self): return atom_store

adapt = sql_adapt.Adapter(DummyNeon())

t1 = atom.AtomType('tab1-type')
t1.add_table('tab1', ('SELECT guid FROM tab1 WHERE id = ?', ['id']))
atom_store.reg_type(t1)

t2 = atom.AtomType('tab2-type')
t2.add_table('tab2')
atom_store.reg_type(t2)

try:
    adapt.insert(sql_adapt.InsertDesc('tab1', None, [None, 'hello']))
    adapt.insert(sql_adapt.InsertDesc('tab1', None, [None, 'hello']))
    adapt.insert(sql_adapt.InsertDesc('tab1', None, [None, 'hello']))
    adapt.insert(sql_adapt.InsertDesc('tab1', None, [None, 'hello']))
    adapt.insert(sql_adapt.InsertDesc('tab1', None, [None, 'hello']))

    fields = backend.table_schema('tab2')
    values = {}
    values[0] = [None, 'hello', 'world', 'is', 'there']
    values[1] = ['dummy', 'weee', 'w', 'i', 't']
    values[2] = ['__', 'e', 'w', 'T', 't']

    for i in xrange(3):
        adapt.insert(sql_adapt.InsertDesc('tab2', None, values[i]))

    for i in xrange(4):
        assert atom_store.get_atom(guid.Guid('testing-id', i)) is None
    a = atom_store.get_atom(guid.Guid('testing-id', 4))
    assert a.get_guid() == guid.Guid('testing-id', 4)
    assert a.fields == {'tab1': [{'guid': 'testing-id:4', 'id': 'hello'}]}

    for i in xrange(5, 8):
        a = atom_store.get_atom(guid.Guid('testing-id', i))
        assert a.get_guid() == guid.Guid('testing-id', i)

        v = dict(zip(fields, values[i-5]))
        for k in v.keys():
            if k == 'guid':
                assert a.fields['tab2'][0][k] == str(guid.Guid('testing-id', i))
            else:
                assert a.fields['tab2'][0][k] == v[k]
                
except AssertionError:
    log.error('DEBUG DUMP --------------------------------------------------')
    backend.execute('SELECT * from neon_atom_meta')
    for i in backend.fetchall():
        log.error(i)

    log.error('DEBUG DUMP tab1 ----------------------------------------------')
    backend.execute('SELECT * from tab1')
    for i in backend.fetchall():
        log.error(i)

    log.error('DEBUG DUMP tab2 ----------------------------------------------')
    backend.execute('SELECT * from tab2')
    for i in backend.fetchall():
        log.error(i)

    raise
